package com.example.hello.controller;

import com.example.hello.pojo.CreditLog;
import com.example.hello.pojo.Res;
import com.example.hello.service.CreditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/credit")
public class CreditController {

    @Autowired private CreditService creditService;

    /** 用户归还图书时调用（也可不暴露为接口，而在归还流程中内部调用） */
    @GetMapping("/return")
    public Res onReturn(
            @RequestParam Long userId,
            @RequestParam Long borrowId,
            @RequestParam String borrowDate,  // 直接用 String
            @RequestParam String returnDate
    ) {
        // 1. 按 ISO_LOCAL_DATE_TIME 解析
        LocalDateTime bd = LocalDateTime.parse(borrowDate);
        LocalDateTime rd = LocalDateTime.parse(returnDate);
        // 2. 转成 Date 或 Instant
        Date bdDate = Date.from(bd.atZone(ZoneId.systemDefault()).toInstant());
        Date rdDate = Date.from(rd.atZone(ZoneId.systemDefault()).toInstant());
        // 3. 调用业务
        creditService.onReturn(userId, borrowId, bdDate, rdDate);
        return Res.success();
    }

    /** 查询当前信誉度 */
    @GetMapping("/{userId}")
    public Res getCredit(@PathVariable Long userId) {
        Integer c = creditService.getCurrentCredit(userId);
        return Res.success(c);
    }

    /** 查询信誉流水 */
    @GetMapping("/logs/{userId}")
    public Res getLogs(@PathVariable Long userId) {
        List<CreditLog> logs = creditService.getCreditLogs(userId);
        return Res.success(logs);
    }
}